package tan.dft.gps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.json.JSONObject;

import tan.dft.json.DirectionsJSONParser;
import tan.dft.quanly.Quanly;
import android.app.Dialog;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class Danduong extends FragmentActivity implements LocationListener,
		OnInfoWindowClickListener {

	private GoogleMap googleMap;
	private ArrayList<LatLng> markerPoints;
	private ArrayList<Quanly> array;
	private Geocoder geocoder;
	private List<Address> addresses;
	private String add;
	private LatLng latLng, latLng2;
	private RadioButton rbDriving, rbWalking;
	private RadioGroup rgModes;
	int mMode = 0;
	final int MODE_DRIVING = 0;
	final int MODE_WALKING = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.danduong);
		rbDriving = (RadioButton) findViewById(R.id.rb_driving);
		rbWalking = (RadioButton) findViewById(R.id.rb_walking);
		rgModes = (RadioGroup) findViewById(R.id.rg_modes);

		// Initializing
		markerPoints = new ArrayList<LatLng>();
		// Getting Google Play availability status
		int status = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getBaseContext());
		// Showing status
		if (status != ConnectionResult.SUCCESS) { // Google Play Services are
													// not available
			int requestCode = 10;
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
					requestCode);
			dialog.show();
		} else {
			// Google Play Services are available
			// Getting reference to the SupportMapFragment of activity_main.xml
			SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map);
			// Getting GoogleMap object from the fragment
			googleMap = fm.getMap();
			if (googleMap != null) {
				// Enable MyLocation Button in the Map
				googleMap.setMyLocationEnabled(true);
				// Setting onclick event listener for the map
				googleMap.setOnMapClickListener(new OnMapClickListener() {
					@Override
					public void onMapClick(LatLng point) {
						// Already two locations
						if (markerPoints.size() > 1) {
							markerPoints.clear();
							googleMap.clear();
						}
						// Adding new item to the ArrayList
						markerPoints.add(point);
						// Creating MarkerOptions
						MarkerOptions options = new MarkerOptions();
						// Setting the position of the marker
						options.position(point);
						/**
						 * For the start location, the color of marker is GREEN
						 * and for the end location, the color of marker is RED.
						 */
						try {
							addresses = geocoder.getFromLocation(
									point.latitude, point.longitude, 1);
							String address = addresses.get(0).getAddressLine(0);
							String city = addresses.get(0).getAddressLine(1);
							String country = addresses.get(0).getAddressLine(2);
							add = address + " | " + city + " | " + country;
							options.title(add);
						} catch (IOException e) {
							e.printStackTrace();
						}
						if (markerPoints.size() == 1) {
							options.icon(BitmapDescriptorFactory
									.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
						} else if (markerPoints.size() == 2) {
							options.icon(BitmapDescriptorFactory
									.defaultMarker(BitmapDescriptorFactory.HUE_RED));
						}
						// Add new marker to the Google Map Android API V2
						googleMap.addMarker(options);
						// Checks, whether start and end locations are captured
						if (markerPoints.size() >= 2) {
							LatLng origin = markerPoints.get(0);
							LatLng dest = markerPoints.get(1);
							// Getting URL to the Google Directions API
							String url = getDirectionsUrl(origin, dest);
							DownloadTask downloadTask = new DownloadTask();
							downloadTask.execute(url);
						}
					}
				});
			}
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
			Criteria criteria = new Criteria();
			String provider = locationManager.getBestProvider(criteria, true);
			Location location = locationManager.getLastKnownLocation(provider);
			if (location != null) {
				onLocationChanged(location);
			}
			locationManager.requestLocationUpdates(provider, 20000, 0, this);
			geocoder = new Geocoder(this, Locale.getDefault());
			try {
				addresses = geocoder.getFromLocation(location.getLatitude(),
						location.getLongitude(), 1);
				String address = addresses.get(0).getAddressLine(0);
				String city = addresses.get(0).getAddressLine(1);
				String country = addresses.get(0).getAddressLine(2);
				add = address + " | " + city + " | " + country;
				googleMap.addMarker(new MarkerOptions()
						.position(
								new LatLng(location.getLatitude(), location
										.getLongitude())).title(add)
						.snippet("Hello"));

			} catch (IOException e) {
				e.printStackTrace();
			}

			latLng2 = new LatLng(location.getLatitude(),
					location.getLongitude());

			googleMap.setOnInfoWindowClickListener(this);

			array = getIntent().getParcelableArrayListExtra("mylist");
			if (array != null) {
				for (int i = 0; i < array.size(); i++) {

					Double lat = array.get(i).getLat();
					Double lng = array.get(i).getLng();
					String name = array.get(i).getName();
					latLng = new LatLng(lat, lng);
					geocoder = new Geocoder(this, Locale.getDefault());
					try {
						addresses = geocoder.getFromLocation(lat, lng, 1);
						String address = addresses.get(0).getAddressLine(0);
						String city = addresses.get(0).getAddressLine(1);
						String country = addresses.get(0).getAddressLine(2);
						add = name + " | " + address + " | " + city + " | "
								+ country;
						googleMap.addMarker(new MarkerOptions()
								.position(new LatLng(lat, lng)).title(add)
								.position(latLng).snippet("Hello"));
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

			}

		}
		rgModes.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (markerPoints.size() >= 2) {
					LatLng origin = markerPoints.get(0);
					LatLng dest = markerPoints.get(1);
					String url = getDirectionsUrl(origin, dest);
					DownloadTask downloadTask = new DownloadTask();
					downloadTask.execute(url);
				}
			}
		});
	}

	private String getDirectionsUrl(LatLng origin, LatLng dest) {
		String str_origin = "origin=" + origin.latitude + ","
				+ origin.longitude;
		String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
		String sensor = "sensor=false";
		String mode = "mode=driving";
		if (rbDriving.isChecked()) {
			mode = "mode=driving";
			mMode = 0;
		} else if (rbWalking.isChecked()) {
			mode = "mode=walking";
			mMode = 2;
		}
		String parameters = str_origin + "&" + str_dest + "&" + sensor + "&"
				+ mode;
		String output = "json";
		String url = "https://maps.googleapis.com/maps/api/directions/"
				+ output + "?" + parameters;
		return url;
	}

	/** A method to download json data from url */
	private String downloadUrl(String strUrl) throws IOException {
		String data = "";
		InputStream iStream = null;
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL(strUrl);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.connect();
			iStream = urlConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					iStream));
			StringBuffer sb = new StringBuffer();
			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			data = sb.toString();
			br.close();
		} catch (Exception e) {
			Log.d("Exception while downloading url", e.toString());
		} finally {
			iStream.close();
			urlConnection.disconnect();
		}
		return data;
	}

	private class DownloadTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... url) {
			String data = "";
			try {
				data = downloadUrl(url[0]);
			} catch (Exception e) {
				Log.d("Background Task", e.toString());
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			ParserTask parserTask = new ParserTask();
			parserTask.execute(result);
		}
	}

	/** A class to parse the Google Places in JSON format */
	private class ParserTask extends
			AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
		@Override
		protected List<List<HashMap<String, String>>> doInBackground(
				String... jsonData) {
			JSONObject jObject;
			List<List<HashMap<String, String>>> routes = null;
			try {
				jObject = new JSONObject(jsonData[0]);
				DirectionsJSONParser parser = new DirectionsJSONParser();
				routes = parser.parse(jObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return routes;
		}

		// Executes in UI thread, after the parsing process
		@Override
		protected void onPostExecute(List<List<HashMap<String, String>>> result) {
			ArrayList<LatLng> points = null;
			PolylineOptions lineOptions = null;
			for (int i = 0; i < result.size(); i++) {
				points = new ArrayList<LatLng>();
				lineOptions = new PolylineOptions();
				List<HashMap<String, String>> path = result.get(i);
				for (int j = 0; j < path.size(); j++) {
					HashMap<String, String> point = path.get(j);
					double lat = Double.parseDouble(point.get("lat"));
					double lng = Double.parseDouble(point.get("lng"));
					LatLng position = new LatLng(lat, lng);
					points.add(position);
				}

				lineOptions.addAll(points);
				lineOptions.width(5);
				if (mMode == MODE_DRIVING)
					lineOptions.color(Color.RED);
				else if (mMode == MODE_WALKING)
					lineOptions.color(Color.BLUE);
			}
			if (result.size() < 1) {
				Toast.makeText(getBaseContext(), "No Points",
						Toast.LENGTH_SHORT).show();
				return;
			}
			googleMap.addPolyline(lineOptions);
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		double latitude = location.getLatitude();
		double longitude = location.getLongitude();
		LatLng latLng = new LatLng(latitude, longitude);
		googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
		googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		
		String url = getDirectionsUrl(latLng2, marker.getPosition());
		DownloadTask downloadTask = new DownloadTask();
		downloadTask.execute(url);
	}

}
